package com.itheima.tlias84.exception;

import com.itheima.tlias84.Util.ResultUtil;
import org.springframework.http.HttpStatus;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.List;
import java.util.StringJoiner;

/**
 * 因为我们无法使用try-catch捕获进入controller之前的异常,但是可以使用aop对controller进行调用之前的增强
 * 因此@RestControllerAdvice相当于环绕通知controller
 */
@RestControllerAdvice
public class GlobalExceptionHandler {
    @ExceptionHandler(ArithmeticException.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public ResultUtil handleArithmeticException(ArithmeticException exception) {
        return ResultUtil.fail(exception.getMessage());

    }

    @ExceptionHandler(MethodArgumentNotValidException.class)
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public ResultUtil handleMethodArgumentNotValidException(MethodArgumentNotValidException exception) {
        //获取单个校验信息
//        String defaultMessage = exception.getFieldError().getDefaultMessage();
//        Object rejectedValue = exception.getFieldError().getRejectedValue();
        //获取全部校验信息
        BindingResult bindingResult = exception.getBindingResult();
        List<FieldError> fieldErrors = bindingResult.getFieldErrors();
        // 使用StringJoiner拼接所有校验失败的信息，以","分隔
        StringJoiner stringJoiner = new StringJoiner(",", "[", "]");
        for (FieldError fieldError : fieldErrors) {
            stringJoiner.add(fieldError.getDefaultMessage());
        }
        // 返回校验失败的全部信息
        return ResultUtil.fail(stringJoiner.toString());
        // return ResultUtil.fail(defaultMessage, rejectedValue);
    }

}
